package com.whales.shared.util;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.ArrayList;

public class NetworkUtil {
	public static final int PORT = 9;
	public static final String WAKE_CFG_PATH = "C:/wol/WakeMeOnLan.cfg";

	public static boolean wakeOnLan(String ipStr) {
		try {
			System.out.println("wakeOnLan... C:/wol/WakeMeOnLan.exe /wakeup "+ipStr);
			Process p1 = Runtime.getRuntime().exec("C:/wol/WakeMeOnLan.exe /wakeup "+ipStr);
			int returnVal = p1.waitFor();
			boolean success = (returnVal==0);
			return success;
		} catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}
	
	public static boolean wakeOnLan(String ipStr, String macStr) {

		boolean bReturn = true;
		try {
			
			if(anyframe.common.util.StringUtil.isEmpty(ipStr)){
				return false;
			}
			//////////////////////////// start added
			String subStr = "255.255.255.255";
			byte[] hostAddr   = InetAddress.getByName(ipStr).getAddress();
		    byte[] subnetAddr = InetAddress.getByName(subStr).getAddress();
		    
		    byte[] broadAddr  = new byte[4];    
		     for (int i = 0; i < 4; i++)       
		    	 broadAddr[i]  = (byte) (hostAddr[i] | (~subnetAddr[i]));
		     //////////////////////////// end added by sky
		     
			byte[] macBytes = getMacBytes(macStr);
			byte[] bytes = new byte[6 + 16 * macBytes.length];
			for (int i = 0; i < 6; i++) {
				bytes[i] = (byte) 0xff;
			}
			for (int i = 6; i < bytes.length; i += macBytes.length) {
				System.arraycopy(macBytes, 0, bytes, i, macBytes.length);
			}
			//String[] ipArr = ipStr.split("[.]");
			//if(ipArr.length > 4){
			//	return false;
			//}
			//String ipClass = ipArr[0] + "."+ipArr[1] + "."+ipArr[2] + ".255";
//			String ipClass = "255.255.255.255";
			//InetAddress address = InetAddress.getByName(ipClass);
			InetAddress address   = InetAddress.getByAddress(broadAddr);
			DatagramPacket packet = new DatagramPacket(bytes, bytes.length,address, PORT);
			DatagramSocket socket = new DatagramSocket();
			socket.send(packet);
			socket.close();

			System.out.println("Wake-on-LAN packet sent..."+ address.toString() +","+macStr);
		} catch (Exception e) {
			System.out.println("Failed to send Wake-on-LAN packet: "+ e);
			bReturn = false;
		}
		return bReturn;
	}
	
	public static boolean ping(String ip){
		try {
			Process p1 = java.lang.Runtime.getRuntime().exec("ping -n 1 "+ip);
			int returnVal = p1.waitFor();
			boolean reachable = (returnVal==0);
			return reachable;
		} catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}

	private static byte[] getMacBytes(String macStr) throws IllegalArgumentException {
		byte[] bytes = new byte[6];
		String[] hex = macStr.split("(\\:|\\-)");
		if (hex.length != 6) {
			throw new IllegalArgumentException("Invalid MAC address.");
		}
		try {
			for (int i = 0; i < 6; i++) {
				bytes[i] = (byte) Integer.parseInt(hex[i], 16);
			}
		} catch (NumberFormatException e) {
			throw new IllegalArgumentException("Invalid hex digit in MAC address.");
		}
		return bytes;
	}
	
	// pc 등록 , 수정시
	public static void registWakeOnConfigFile(String macAddress, String ipAddress){

		try {

			JIniFile ini = new JIniFile(WAKE_CFG_PATH);

			ArrayList<String> secList = ini.ReadSections();

			for(String section : secList){
				String secIp = ini.ReadString(section, "IPAddress", "xx.xx.xx.xx"); // key, default ip

				if(ipAddress.equals(secIp)){
					ini.EraseSection(section);
				}
			}

			if(ini.SectionExist("Device_" + macAddress)){
				System.out.println("exist");
				ini.WriteString("Device_" + macAddress, "IPAddress", ipAddress);
				ini.UpdateFile();
			}else{

				System.out.println("not exist");
				ini.WriteString("Device_" + macAddress, "BroadcastAddress", "");
				ini.WriteString("Device_" + macAddress, "PortNumber", "0");
				ini.WriteString("Device_" + macAddress, "UseBroadcastAddress", "0");
				ini.WriteString("Device_" + macAddress, "UsePortNumber", "0");
				ini.WriteString("Device_" + macAddress, "IPAddress", ipAddress);
				ini.WriteString("Device_" + macAddress, "Workgroup", "");
				ini.WriteString("Device_" + macAddress, "Name", "");
				ini.WriteString("Device_" + macAddress, "UserText", "");

				ini.UpdateFile();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	//PC 삭제시
	public static void deleteWakeOnConfigFile(String ipAddress){

		try{
			JIniFile ini = new JIniFile(WAKE_CFG_PATH);
			ArrayList<String> secList = ini.ReadSections();

			for(String section : secList){
				String secIp = ini.ReadString(section, "IPAddress", "xx.xx.xx.xx"); // key, default ip

				if(ipAddress.equals(secIp)){
					ini.EraseSection(section);
				}
			}

			ini.UpdateFile();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
